package u.can.i.up.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.commons.io.IOUtils;
import org.apache.commons.net.ftp.FTPClient;

public class FtpUtil {

	public static void downloadFileFromFtp(String ip, String username, String password, String ftp_path,
			String locate_path) {
		FTPClient ftpClient = new FTPClient();
		FileOutputStream fos = null;
		try {
			ftpClient.connect(ip);
			ftpClient.login(username, password);
			ftpClient.setBufferSize(1024);
			ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
			ftpClient.setFileTransferMode(FTPClient.STREAM_TRANSFER_MODE);
			ftpClient.setControlEncoding("UTF-8");
			ftpClient.enterLocalPassiveMode();
			new File(locate_path).getParentFile().mkdirs();
			fos = new FileOutputStream(locate_path);
			ftpClient.retrieveFile(ftp_path, fos);
			fos.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			IOUtils.closeQuietly(fos);
			try {
				ftpClient.disconnect();
			} catch (IOException e) {
				e.printStackTrace();
				throw new RuntimeException("关闭FTP连接发生异常！", e);
			}
		}
	}
}
